package annotation.demo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Table("user")
public class UserBean {
	
	@Column("id")
	private int id;
	
	@Column("name")
	private String name;
	
	@Column("email")
	private String email;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	
	public String query(UserBean user) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
		
		StringBuilder sb = new StringBuilder();
		//1.获取到class
		Class<?> clazz = user.getClass();
		//拿到annotation里的值
		boolean isExistTable = clazz.isAnnotationPresent(Table.class);
		if(isExistTable) {
			Table table = (Table)clazz.getAnnotation(Table.class);
			sb.append("select * from ").append(table.value()).append(" where 1=1");
		}
		
		Field[] fields = clazz.getDeclaredFields();
		for(Field field : fields) {
			
			boolean isExsitColumn = field.isAnnotationPresent(Column.class);
			if(isExsitColumn) {
				Column column = (Column) field.getAnnotation(Column.class);
				String value = (String)column.value();
				Method method = clazz.getMethod("get"+value.substring(0,1).toUpperCase()+value.substring(1));
				
				Object result = method.invoke(user);
				if(result != null && result instanceof String) {
					String tmp = (String) result;
					if(tmp.contains(",")) {
						sb.append(" and ");
						sb.append(field.getName()).append(" in ").append("(").append(result).append(")");
						continue;
					}
					
					sb.append(" and " );
					sb.append(field.getName()).append("=").append("'").append(result).append("'");
				}else if(result != null && result instanceof Integer) {
					sb.append(" and ");
					sb.append(field.getName()).append("=").append(result);
				}
			}
		}
		
		
		
		return sb.toString();
	}

}
